<template>
  <div class="h-full">
    <a-card class="mb-2">
      <a-form class="w-full form-style-flex justify-between">
        <a-form-item class="!mb-0">
          <SelectTable
            v-model:value="currentUser.brName"
            custom-input
            type="患者"
            placeholder="姓名/助记码/手机号/卡号/证件号码"
            large="large"
            class="w-[350px]"
            @select="onSelectUser"
          />
        </a-form-item>
        <a-form-item class="!mb-0">
          <a-button type="primary" size="large" class="mr-4" @click="addOpen = true">新伤病员</a-button>
          <a-button type="primary" size="large" ghost @click="medicalOpen = true">就诊记录</a-button>
        </a-form-item>
      </a-form>
    </a-card>
    <div class="flex flex-col flex-1 overflow-hidden">
      <PatientInfoHeader :patient-info="currentUser" :show-user-info="false">
        <div class="flex justify-between flex-1 pl-4">
          <div>
            <div class="flex items-center">
              <LabelValue class="" label="人员属性" :width="140" :value="currentUser.rysx" />
              <LabelValue class="ml-4" label="军种" :width="140" :value="currentUser.brJz" />
              <LabelValue class="ml-4" label="卡号" :width="200" :value="currentUser.brId" />
              <LabelValue class="ml-4" label="入伍日期" :width="280" :tooltip="true" :value="currentUser.brRwny" />
            </div>
            <div class="flex items-center">
              <LabelValue class="" label="部职别" :width="140" :value="currentUser.brBb" />
              <LabelValue class="ml-4" label="军衔" :width="140" :value="currentUser.brJx" />
              <LabelValue class="ml-4" :width="200" label="部队番号" :value="currentUser.brBdfh" />
              <LabelValue class="ml-4" :width="200" label="上次就诊时间" :value="currentUser.xxx" />
            </div>
          </div>
          <div>
            <a-button type="primary" size="large" class="mr-4" :disabled="!currentUser.brId" :loading="loading" @click="onRegister">开始就诊</a-button>
            <a-button type="primary" size="large" :disabled="!currentUser.brId" @click="onRegisterEnd">结束就诊</a-button>
          </div>
        </div>
      </PatientInfoHeader>
      <div class="flex flex-1 mt-2 overflow-hidden">
        <a-card class="flex-1 overflow-auto" :body-style="{ padding: '0 8px', height: '100%', overflow: 'hidden' }">
          <a-tabs
            v-model:activeKey="activeKey"
            destroy-inactive-tab-pane
            :class="store.currentPatient?.jzbh ? 'h-full' : 'tabs-disabled h-full'"
            @change="onChangeTabs"
          >
            <a-tab-pane key="1" tab="病历">
              <TabCase :case-data="store.currentPatient" :active-key="activeKey" @success="onCaseSuccess" />
            </a-tab-pane>
            <a-tab-pane key="3" tab="处置">
              <TabDispose />
            </a-tab-pane>
            <a-tab-pane key="4" tab="西成药" :disabled="!isHasDiagnosis">
              <TabWesternMedicine />
            </a-tab-pane>
            <!-- 是否启用门诊医生工作站子频道_检查 -->
            <a-tab-pane v-if="systemConfig.isInspect" key="6" tab="检查">
              <TabCheck />
            </a-tab-pane>
            <!-- 是否启用门诊医生工作站子频道_检验 -->
            <a-tab-pane v-if="systemConfig.isInspection" key="7" tab="检验">
              <TabLaboratory :patient-data="store.currentPatient" />
            </a-tab-pane>
            <!-- 是否启用门诊医生工作站子频道_手术 -->
            <!-- <a-tab-pane v-if="systemConfig.isOperation" key="8" tab="留观">
              <TabOperation />
            </a-tab-pane> -->
            <!-- 是否启用门诊医生工作站子频道_入院申请 -->
            <a-tab-pane v-if="systemConfig.isApplication" key="9" tab="入院申请">
              <TabHospitalApply />
            </a-tab-pane>
            <a-tab-pane key="10" tab="证明书">
              <TabCertificate />
            </a-tab-pane>
          </a-tabs>
        </a-card>
        <a-card class="w-72 ml-2 history-card" :class="historyExpand ? 'history-expand' : ''" :body-style="{ paddingTop: 0 }">
          <div class="history-expand-btn" @click="() => (historyExpand = !historyExpand)">
            <DoubleLeftOutlined v-if="historyExpand" />
            <DoubleRightOutlined v-else />
          </div>
          <div v-if="historyExpand" class="pt-12 text-primary font-semibold">历史</div>
          <a-tabs v-model:activeKey="leftActiveKey" centered>
            <a-tab-pane key="1">
              <template #tab>
                <div class="px-5 text-center">历史</div>
              </template>
              <div class="overflow-auto" style="height: calc(100vh - 200px)">
                <HistoryCase :open="historyExpand" @success="onCopySuccess" />
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </div>
    </div>
    <PatientTableModal v-model:open="registrationOpen" />
    <MedicalRecords v-model:open="medicalOpen" @success="getData" />
    <FilesAdd v-model:open="addOpen" @success="getVisitNumber" />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { DoubleRightOutlined, DoubleLeftOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import { getSystemConfig } from '@/utils/systemConfig'
import userStore from '@/store/user.js'

import FilesAdd from '../components/FilesAdd'
import useStore from './store'
import TabCase from './TabCase'
import TabCheck from './TabCheck'
import TabDispose from './TabDispose'
// import TabOperation from './TabOperation'
import TabLaboratory from './TabLaboratory'
import TabCertificate from './TabCertificate'
import TabWesternMedicine from './TabWesternMedicine'
import TabHospitalApply from './TabHospitalApply'
import HistoryCase from './components/HistoryCase'
import PatientTableModal from './components/PatientTableModal'
import MedicalRecords from './components/MedicalRecords'

const { empId } = userStore()
const router = useRouter()
const route = useRoute()
const store = useStore()
const patientListRef = ref()
const historyExpand = ref(true)
const activeKey = ref(router.currentRoute.value.query.tab || '1')
const leftActiveKey = ref('1')
const isHasDiagnosis = ref(false)
const currentUser = ref({})
const registrationOpen = ref(false)
const medicalOpen = ref(false)
const addOpen = ref(false)
const systemConfig = {
  isTreatment: getSystemConfig('IS_OUTP_OPHTH_TREATMENT_PIAN') === '1', //治疗方案
  isMedicine: getSystemConfig('ENABLE_OUTP__SINGLE_ADVICEORDER_MODE') === '1', //0处置、西成药1医嘱
  isWestMedicine: getSystemConfig('ISSUE_DRUG_ORDER_WITHOUT_ICD10') === '0', // 西成药
  isCentreMedicine: getSystemConfig('IS_OUTP__DOCTOR_TCM') === '1', // 中草药
  isReport: getSystemConfig('IS_OUTP_OPHTH_SPECIAL_EXAMINATION') === '1', // 特检报告
  isOptometry: getSystemConfig('IS_OUTP_OPHTH_TRY_OPTOMETRY') === '1', // 验光试戴确认
  isInspect: getSystemConfig('IS_OUTP__DOCTOR_RIS') === '1', // 检查
  isInspection: getSystemConfig('IS_OUTP__DOCTOR_LIS') === '1', // 检验
  isOperation: getSystemConfig('IS_OUTP__DOCTOR_OPERATION') === '1', // 手术
  isApplication: getSystemConfig('IS_OUTP__DOCTOR_INP') === '1', // 入院申请
  isDocument: getSystemConfig('IS_OUTP__DOCTOR_OPERATION_DOCUMENT') === '1' // 手术文书
}

const getData = async (jzbh) => {
  const { code, msg, data } = await post('/outp/mzys/getOutpRecordInfo', {
    mzjlbh: jzbh
  })
  if (code !== 0) return message.error(msg || '获取病历信息失败')
  store.currentPatient = data
  if (data.bcLczdZdmc) {
    isHasDiagnosis.value = true
  } else {
    isHasDiagnosis.value = false
  }
}

const onCaseSuccess = () => {
  getData(store.currentPatient.jzbh)
  isHasDiagnosis.value = true
  patientListRef.value?.queryList(false)
}

const onCopySuccess = () => {
  activeKey.value = '1'
  patientListRef.value?.queryList(false)
}

const isDev = import.meta.env.DEV
//切换Tab标签
const onChangeTabs = () => {
  if (isDev) {
    router.push({
      path: router.currentRoute.value.path,
      query: {
        tab: activeKey.value
      }
    })
  }
}

const onSelectUser = (select) => {
  currentUser.value = select
  getVisitNumber(select)
  store.currentPatient = {}
}
//根据病人ID获取就诊编号
const getVisitNumber = async (select) => {
  const { code, msg, data } = await post('/outp/mzdj/getBrRegisteredToDay', {
    brId: select.brId,
    ksdm: getSystemConfig('REGISTER_DEFAULT_DEPT_CODE')
  })
  if (code !== 0) return message.error(msg)
  if (data?.jzbh) {
    getData(data.jzbh)
  } else {
    const { code, data = {} } = await get('/common/patient/getPatientInfo?br_id=' + select.brId)
    if (code !== 0) return message.error('获取患者信息失败')
    store.currentPatient = data
  }
}
const loading = ref(false)
const onRegister = async () => {
  // ghfybh: 'YP000000490', //todo
  // zlfybh: 'YP000000491', //todo
  loading.value = true
  const { code, msg, jzbhs } = await post(
    '/outp/mzdj/doRegister',
    {
      ...currentUser.value,
      ghfybh: getSystemConfig('NAVYHIS_MODE_REGISTRATION_FEE_CODE'), //todo
      zlfybh: getSystemConfig('NAVYHIS_MODE_CONSULTATION_FEE_CODE'), //todo
      empId,
      ghlbid: getSystemConfig('REGISTER_DEFAULT_CATEGORY_CODE'),
      ksdm: getSystemConfig('REGISTER_DEFAULT_DEPT_CODE'),
      ksdms: [getSystemConfig('REGISTER_DEFAULT_DEPT_CODE')],
      brAge: currentUser.value.brAge?.match(/\d+/g).map(Number)[0],
      ssje: 0,
      gzzf: 0
    },
    { loading: true }
  )
  loading.value = false

  if (code !== 0) return message.error(msg || '挂号失败')
  message.success('挂号成功')
  getData(jzbhs[0])
}

// 结束就诊
const onRegisterEnd = async () => {
  const { code, msg } = await post('/outp/mzys/modifyPatientClinicStatus', {
    ghzt: 3,
    jzbh: store.currentPatient?.jzbh,
    ysbh: store.currentPatient?.ysbh
  })
  if (code !== 0) return message.error(msg)
  message.success('成功')
  store.currentPatient = {}
}

watch(
  () => store.currentPatient.jzbh,
  () => {
    currentUser.value = store.currentPatient
    activeKey.value = '1'
  },
  { immediate: true }
)
watch(
  () => activeKey.value,
  (val) => {
    if (val === '1') {
      if (store.currentPatient.jzbh) getData(store.currentPatient.jzbh)
    }
  }
)
watchEffect(() => {
  if (route.query?.brId) {
    getVisitNumber(route.query)
  }
})
</script>
<style lang="less" scoped>
:deep(.ant-tabs-tab) {
  padding: 12px 24px;
}
.tabs-disabled {
  cursor: not-allowed;
  filter: opacity(0.5);
  pointer-events: none;
}
:deep(.ant-tabs-content) {
  height: calc(100% - 8px);
}
.history-card {
  transition: all 0.3s;
}
.history-expand {
  width: 56px !important;
  :deep(.ant-tabs) {
    visibility: hidden;
  }
}
.history-expand-btn {
  position: absolute;
  top: 4px;
  right: 12px;
  z-index: 99;
  padding: 8px;
  color: var(--primary-color);
  background-color: var(--secondary-color);
  border-radius: 8px;
  cursor: pointer;
}

.next-btn {
  color: #fff;
  background-color: #369c17;
  border: 1px solid #369c17;
  &:hover {
    color: #fff;
    background-color: #369c17dd;
  }
}
.recall-btn {
  color: #e99b09;
  background-color: #e99b0940;
  border: 1px solid #e99b09;
  &:hover {
    color: #e99b09;
  }
}
</style>
